package com.jufa_3.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jufa_3.common.*;
import com.jufa_3.dto.SelRetInfo;
import com.jufa_3.dto.SelectInfo;
import com.jufa_3.entity.InterUseRecord;
import com.jufa_3.mapper.InterUseRecordMapper;
import com.juhe.sdk.ApiClient;
import com.juhe.sdk.common.Result;
import com.juhe.sdk.reqeust.StudentVerifyRequest;
import com.juhe.sdk.response.LawSuitResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Repository
@PropertySource(value = "classpath:pdf-titles.properties", encoding = "UTF-8")
public class SelectInterface {

    @Resource
    private Environment config;

    public static String TIAN_YAN_APPID = "jFtxWcddLGv79fPe";

    public static String TIAN_YAN_APP_SECURITY = "jFtxWcddLGv79fPe2JS2unO8c6F2beuT";

    public static String TIAN_YAN_APP_URL = "https://api.shumaidata.com/v4/business4/get";
    //主要查询以下类型
    @Autowired
    private InterUseRecordMapper interUseRecordMapper;

//    public JSONObject zewuGrajjcxxhy(SelectInfo sif) {
//        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
//        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
//            return JSONObject.parseObject(iur.getQueryInfo());
//        }
//        JSONObject params = new JSONObject();
//        params.put("cert_name", sif.getName());
//        params.put("cert_no", sif.getCardNum());
//        String receive;
//        try {
//            receive = AesUtils.send("https://www.zewubeidiao.com:8087/dataMiddle/api/shuJuBaoApiQuery", disposeZewuPublicParams("1", params));
//            log.warn("则悟返回：" + receive);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        JSONObject receiveJs = JSONObject.parseObject(receive);
//        iur = new InterUseRecord(
//                sif.getId(),
//                sif.getSourceType(),
//                "个人案件基础信息核验",
//                sif.getKeyWord(),
//                receiveJs.getString("trans_id"),
//                receiveJs.getString("desc"));
//        if (receiveJs.getInteger("code") == 0) {
//            JSONObject data = JSONArray.parseArray(receiveJs.getString("data")).getJSONObject(0).getJSONObject("detail");
//            receiveJs.replace("data", data);
//            iur.setQueryInfo(receiveJs.toJSONString());
//        }
//        interUseRecordMapper.addInterUseRecord(iur);
//        return receiveJs;
//    }
//
//    public JSONObject zewuFyxxxq(SelectInfo sif) {
//        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
//        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
//            return JSONObject.parseObject(iur.getQueryInfo());
//        }
//        JSONObject params = new JSONObject();
//        params.put("cert_name", sif.getName());
//        params.put("cert_no", sif.getCardNum());
//        params.put("mobile", sif.getMobile());
//        String receive;
//        try {
//            receive = AesUtils.send("https://www.zewubeidiao.com:8087/dataMiddle/api/baiRongApiQuery", disposeZewuPublicParams("4", params));
//            log.warn("则悟返回：" + receive);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        JSONObject receiveJs = JSONObject.parseObject(receive);
//        iur = new InterUseRecord(
//                sif.getId(),
//                sif.getSourceType(),
//                "法院信息详情-个人高级版",
//                sif.getKeyWord(),
//                receiveJs.getString("trans_id"),
//                receiveJs.getString("desc"));
//        if (receiveJs.getInteger("code") == 0) {
//            JSONObject data = JSONObject.parseObject(receiveJs.getString("data"));
//            JSONObject entryArs = new JSONObject();
//            if ("1".equals(data.getJSONObject("Flag").getString("courtdetailpro"))) {
//                JSONObject courtDetailPro = data.getJSONObject("CourtDetailPro");
//                if (courtDetailPro.getInteger("count") != 0) {
//                    JSONArray entryList = courtDetailPro.getJSONArray("entryList");
//                    for (int i = 0; i < entryList.size(); i++) {
//                        JSONObject entry = entryList.getJSONObject(i);
//                        String dataType = entry.getString("dataType");
//                        if (entryArs.containsKey(dataType)) {
//                            entryArs.getJSONArray(dataType).add(entry);
//                        } else {
//                            JSONArray entrys = new JSONArray();
//                            entrys.add(entry);
//                            entryArs.put(dataType, entrys);
//                        }
//                    }
//                    receiveJs.replace("data", entryArs);
//                }
//            }
//            iur.setQueryInfo(receiveJs.toJSONString());
//        }
//        interUseRecordMapper.addInterUseRecord(iur);
//        return receiveJs;
//    }

//    public JSONObject zewuFyxxxq(SelectInfo sif) {
//        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
//        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
//            return JSONObject.parseObject(iur.getQueryInfo());
//        }
//        JSONObject params = new JSONObject();
//        params.put("cert_name", sif.getName());
//        params.put("cert_no", sif.getCardNum());
//        params.put("mobile", sif.getMobile());
//        String receive;
//        try {
//            receive = AesUtils.send("https://www.zewubeidiao.com:8087/dataMiddle/api/baiRongApiQuery", disposeZewuPublicParams("4", params));
//            log.warn("则悟返回：" + receive);
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//        JSONObject receiveJs = JSONObject.parseObject(receive);
//        iur = new InterUseRecord(
//                sif.getId(),
//                sif.getSourceType(),
//                "法院信息详情-个人高级版",
//                sif.getKeyWord(),
//                receiveJs.getString("trans_id"),
//                receiveJs.getString("desc"));
//        if (receiveJs.getInteger("code") == 0) {
//            JSONObject data = JSONObject.parseObject(receiveJs.getString("data"));
//            JSONObject entryArs = new JSONObject();
//            if ("1".equals(data.getJSONObject("Flag").getString("courtdetailpro"))) {
//                JSONObject courtDetailPro = data.getJSONObject("CourtDetailPro");
//                if (courtDetailPro.getInteger("count") != 0) {
//                    JSONArray entryList = courtDetailPro.getJSONArray("entryList");
//                    for (int i = 0; i < entryList.size(); i++) {
//                        JSONObject entry = entryList.getJSONObject(i);
//                        String dataType = entry.getString("dataType");
//                        if (entryArs.containsKey(dataType)) {
//                            entryArs.getJSONArray(dataType).add(entry);
//                        } else {
//                            JSONArray entrys = new JSONArray();
//                            entrys.add(entry);
//                            entryArs.put(dataType, entrys);
//                        }
//                    }
//                    receiveJs.replace("data", entryArs);
//                }
//            }
//            iur.setQueryInfo(receiveJs.toJSONString());
//        }
//        interUseRecordMapper.addInterUseRecord(iur);
//        return receiveJs;
//    }

    public JSONObject zewuGrajjcxxhy(SelectInfo sif) {
        JSONObject retuenJs = new JSONObject();
        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
            return JSON.parseObject(iur.getQueryInfo());
        }
        //2.准备参数
        StudentVerifyRequest params = new StudentVerifyRequest();
        params.setIdCardNo(sif.getCardNum());
        params.setFullName(sif.getName());
        try {
            Result<LawSuitResponse> response = juHeReq(2, params);
            if (response.getCode() != 200) {
                log.warn("巨合（司法高级版）异常：" + response);
            }
            iur = new InterUseRecord(
                    sif.getId(),
                    sif.getSourceType(),
                    "个人诉讼记录",
                    sif.getKeyWord());
            // 查询成功
            JSONObject data = JSON.parseObject(JSON.toJSONString(response.getData()));
            iur.setRespId(data.getString("requestId"));
            if (response.getCode() == 200) {
                data.put("code", 200);
                iur.setQueryResult(data.getInteger("resultCode") == 1 ? data.getString("messge") : "查询无结果");
                iur.setQueryInfo(JSON.toJSONString(data));
                interUseRecordMapper.addInterUseRecord(iur);
                return data;
                // 查询失败
            } else {
                retuenJs.put("code", 400);
                retuenJs.put("data", response.getMsg());
                iur.setQueryResult(response.getMsg());
                interUseRecordMapper.addInterUseRecord(iur);
                return retuenJs;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public JSONObject zewuFyxxxq(SelectInfo sif) {
        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
            return JSONObject.parseObject(iur.getQueryInfo());
        }
        try {
            String cert_no = sif.getCardNum();
            String name = sif.getName();
            String phone = sif.getMobile();
            // 订单号
            String out_trade_no = SerialNumberUtil.createBillNo();
            String tran_time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-mm-dd hh:mm:ss"));
            String verify_type = "0632";
            //测试商户号
            String cutomer_code = "1015624528669561";
            String url = "https://api.jizhengyun.com/v1.0/realname/1015624528669561";
            // 3des密钥
            String des_key = "szxQsZZWDsMEt0TjZPcIC3fG";
            //RSA私钥
            String rsa_key = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBALF4IL8iOdAbDjdIwlneQUcogEhQYyfSEI5A183sVRA7f+N+991g3dCAsQ3WeqXvffBpF04jtHy/dV33HoKf+/DZYMTWVGSSjXwblPa5lfoD6zJjO7OAhFduY4OaZDBM54DFPp7WvR1RLK6O9m32YdRIbevR9EsxyQtmc1V0Lex9AgMBAAECgYB8kITro2pQ16yywS8pRQcsmxDvsPzoBln4fyr6LtfF/P1XANeZW1RV9P5RaCnOLruG8zyYbBdTOE95FOslZIXA6862uSlz3NrZmZZT4vml+GB92nGH6dEz4d3Er2bFOlPlrbRUFQPV+bDN5DiaZOpUvo+Eso/IjuXmjWgZvgVwAQJBAOVMCJ7yAJRQBi9f+SlRY+jh3CVg3LDL8ZU1OKGwb0yfTaf2aFlW5Ins/fk2m8AP9+S90iplcgIqge0RnJTUEsECQQDGIvfU5rnLwnSmwORP/gOeKVucx1NR8K+l+L3DqFShCzRw7WDpXW8ymPVMbi0M42SqXVxWJbcW9ntMPoKcZRS9AkEAos2tgU1KZAO9oH2AJ3oGeh+Dc3amu1DSoqI7J3JiVAD33j3yMRyk/9kpKn0/cMrls5+jTT7iB++ueGh8yJ8bAQJBAMWfZR/mDZUNXDpilJawnj0ntSeXrCRDc36Qrf20LM0AFws3yPyaY+nMpIXaMnbza5l9SzbloUt3Bx3SD4YcT+UCQQDSwDoDCC4R8rC1hcAK4vWyKTceTfl9V8eAASTa/q9P8yXZjt9BTta6fygJZa6YOCS/8R0pbHz1Fgux+Q71c4HF";
            ClientRequest molinkRequest = new ClientRequest();
            molinkRequest.setOut_trade_no(out_trade_no);
            molinkRequest.setTran_time(tran_time);
            molinkRequest.setVerify_type(verify_type);
            molinkRequest.setCustomer_code(cutomer_code);
            molinkRequest.setName(new String(name.getBytes(), "UTF-8"));
            molinkRequest.setCert_no(cert_no);
//            molinkRequest.setPhone(phone);
            StringBuilder builder = new StringBuilder();
            builder.append(Constants.out_trade_no.toUpperCase() + "=" + out_trade_no);
            builder.append("&" + Constants.tran_time.toUpperCase() + "=" + tran_time);
            builder.append("&" + Constants.verify_type.toUpperCase() + "=" + verify_type);
            builder.append("&" + Constants.cert_no.toUpperCase() + "=" + cert_no);
            builder.append("&" + Constants.name.toUpperCase() + "=" + name);
//            builder.append("&" + "linkman_cell".toUpperCase() + "=" + phone);
            String sign = RsaSignature.rsaSign(builder.toString(), rsa_key, Constants.CHARSET_UTF8);
            molinkRequest.setSign(sign);
            String json = JSON.toJSONString(molinkRequest);
            byte[] keybyte = des_key.getBytes();
            byte[] requsest = ThreeDesUtil.encryptMode(keybyte, json.getBytes());

            String receive = HttpClientUtils.ysPost(url, ThreeDesUtil.byte2Hex(requsest));
            log.warn("极证云返回（司法）：" + receive);
            JSONObject receiveJs = JSONObject.parseObject(receive);
            JSONObject message = JSONObject.parseObject(receiveJs.getString("message"));
            iur = new InterUseRecord(
                    sif.getId(),
                    sif.getSourceType(),
                    "法院信息详情查询（个人版）",
                    sif.getKeyWord(),
                    receiveJs.getString("out_trade_no"),
                    message.getString("resultMsg"));
            if ("0000".equals(receiveJs.getString("code"))) {
                if (0 == message.getInteger("result")) {
                    JSONArray Result = message.getJSONObject("data").getJSONArray("Result");
                    JSONObject entryArs = new JSONObject();
                    for (int i = 0; i < Result.size(); i++) {
                        JSONObject entry = Result.getJSONObject(i);
                        String dataType = entry.getString("DataType");
                        if (entryArs.containsKey(dataType)) {
                            entryArs.getJSONArray(dataType).add(entry);
                        } else {
                            JSONArray entrys = new JSONArray();
                            entrys.add(entry);
                            entryArs.put(dataType, entrys);
                        }
                    }
                    message.replace("data", entryArs);
                } else {
                    log.warn("查无结果");
                }
                receiveJs.replace("message", message);
                iur.setQueryInfo(receiveJs.toJSONString());
                interUseRecordMapper.addInterUseRecord(iur);
            } else {
                receiveJs.replace("message", message);
            }
            return receiveJs;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    public SelRetInfo getCompanyInfo(SelectInfo sif) {
        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
            return new SelRetInfo(true, JSONObject.parseObject(iur.getQueryInfo()));
        }
        long timeMillis = System.currentTimeMillis();
        StringBuffer params = new StringBuffer();
        params.append("appid=" + TIAN_YAN_APPID);
        params.append("&timestamp=" + timeMillis);
        String str = TIAN_YAN_APPID + "&" + timeMillis + "&" + TIAN_YAN_APP_SECURITY;
        String signMd5 = MD5Utils.stringToMD5(str);
        params.append("&sign=" + signMd5);
        params.append("&keyword=" + sif.getComValue());
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost(TIAN_YAN_APP_URL + "?" + params);
        String result;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
            log.warn("企业信息：" + result);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject info = JSONObject.parseObject(result);
        iur = new InterUseRecord(
                sif.getId(),
                sif.getSourceType(),
                "企业工商全维度版",
                sif.getKeyWord(),
                info.getJSONObject("data").getString("orderNo"),
                info.getString("msg")
        );
        JSONObject companyInfo;
        if (200 == info.getInteger("code")) {
            companyInfo = info.getJSONObject("data").getJSONObject("data");
            companyInfo.put("caipanwenshu", getCompanyJudicialInfo(sif, 1));
            iur.setQueryInfo(companyInfo.toJSONString());
        } else {
            return new SelRetInfo(false, info.getString("msg"));
        }
        interUseRecordMapper.addInterUseRecord(iur);
        return new SelRetInfo(true, companyInfo);
    }

    public JSONObject getCompanyJudicialInfo(SelectInfo sif, Integer pageNum) {
        StringBuffer params = new StringBuffer();
        params.append("key=08f0400663d8437cd40d1e494e19987b");
        params.append("&comType=" + sif.getComType());
        params.append("&comValue=" + sif.getComValue());
        params.append("&pageNum=" + pageNum);
        params.append("&pageSize=50");
        // 获得Http客户端
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        StringEntity entity = new StringEntity(params.toString(), Charset.forName("UTF-8"));
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        // 创建Post请求
        HttpPost httpPost = new HttpPost("http://apis.juhe.cn/company_info/api/legalJudgeBook/query");
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded");
        httpPost.setEntity(entity);
        String result;
        try {
            CloseableHttpResponse response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        JSONObject resultJs = JSONObject.parseObject(result);
        log.warn("企业任职：" + resultJs);
        InterUseRecord iur = new InterUseRecord(
                sif.getId(),
                sif.getSourceType(),
                "企业司法裁判文书",
                sif.getKeyWord() + "&" + pageNum,
                resultJs.getJSONObject("result").getString("orderid"),
                resultJs.getString("reason"));
        if (0 == resultJs.getInteger("error_code")) {
            iur.setQueryInfo(resultJs.getJSONObject("result").getJSONObject("res").toJSONString());
            interUseRecordMapper.addInterUseRecord(iur);
            return resultJs.getJSONObject("result").getJSONObject("res");
        } else {
            return null;
        }
    }

    public SelRetInfo getCompanyPostInfo(SelectInfo sif) {
        InterUseRecord iur = interUseRecordMapper.selectInterQueryInfo(sif.getKeyWord(), true);
        if (iur != null && StringUtils.isNotBlank(iur.getQueryInfo())) {
            return new SelRetInfo(true, JSONObject.parseArray(iur.getQueryInfo()));
        }
        Map<String, Object> productDetailParam = new HashMap<>();
        productDetailParam.put("cardNo", sif.getCardNum());           // 身份证号
        productDetailParam.put("name", sif.getName());                // 姓名
        JSONObject info = RequestTool.yuShan(productDetailParam, "COM114");
        iur = new InterUseRecord(
                sif.getId(),
                sif.getSourceType(),
                "COM114-企业任职报告",
                sif.getKeyWord(),
                info.getString("response_sn"),
                info.getString("retmsg"));
        if ("000000".equals(info.getString("retcode"))) {
            JSONArray retdata = info.getJSONArray("retdata");
            // 查询成功，存入缓存
            iur.setQueryInfo(retdata.toJSONString());
            interUseRecordMapper.addInterUseRecord(iur);
            return new SelRetInfo(true, retdata);
        } else {
            interUseRecordMapper.addInterUseRecord(iur);
            return new SelRetInfo(false, info.getString("retmsg"));
        }
    }

    private Result<LawSuitResponse> juHeReq(int code, StudentVerifyRequest param) {
        //1.准备客户端
        ApiClient apiClient = new ApiClient("http://101.132.253.231/api", "1000003020240626", "ofSgvvRDQE7b2wwcPBAEFAK5Y8MC2Vg6");
        try {
            if (1 == code) {                // 个人涉诉
                Result<LawSuitResponse> result = apiClient.personalLawSuit(param);
                return result;
            } else {
                Result<LawSuitResponse> result = apiClient.personalLawSuitRecord(param);
//                Result<LawSuitResponse> result = apiClient.personalLawSuitRecordV2(param);// 个人诉讼记录
//                if (result.getCode() == 200 && result.getData().getResultCode() == 1) {
//                    result.getData().getDetail().set(0, result.getData().getDetail().getJSONObject(0).getJSONObject("lawsuitStat"));
//                }
                return result;
            }
        } catch (Exception e) {
            log.error("调用出错: {}", e);
            return null;
        }
    }

    private JSONObject disposeZewuPublicParams(String type, JSONObject reqParams) {
        log.warn("则悟请求：" + reqParams);
        JSONObject json = new JSONObject();
        json.put("token", "735822815bb64dd79f114b489213cd3c");
        json.put("timestamp", System.currentTimeMillis() + "");
        json.put("trans_id", new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + RandomStringUtils.randomNumeric(16));
        json.put("type", type);
        json.put("data", AesUtils.encrypt("pFeNMTyFhNRzHrCtNPzc25S7HxtSaR3j", "6KJAG1ZJF63K161E66S3D7ZHN52NHFB5".substring(0, 16), reqParams.toString()));
        return json;
    }
}
